package com.foodchain.controller;

import com.foodchain.consts.Consts;
import com.foodchain.entity.User;
import com.foodchain.util.Misc;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

public class BaseController {

    String redirect(String action) {
        return "redirect:" + action;
    }

    String clientPage(String page) { return getString("client/", page); }

    User loginUser() { return (User) getShiroSession().getAttribute(Consts.Session.LOGIN_USER); }

    void addToShiroSession(String key, Object value) { getShiroSession().setAttribute(key, value); }

    String toJson(boolean success, String message, Object data) { return Misc.toJson(success, message, data); }

    String JsonCode(Integer code,String success,Object data){return  Misc.JsonCode(code,success,data);}

    String getValidErrorMsg(BindingResult result) { return Objects.requireNonNull(result.getFieldError()).getDefaultMessage(); }

    String getStringFromShiroSession(String key) {
        Object obj = getObjectFromShiroSession(key);
        return (null == obj) ? null : obj.toString();
    }

    Object getObjectFromShiroSession(String key) {
        return getShiroSession().getAttribute(key);
    }

    void addToRequest(HttpServletRequest request, String key, Object value) {
        request.setAttribute(key, value);
    }

    @SneakyThrows(IOException.class)
    void toWeb(HttpServletResponse response, Object object) {
        response.setContentType("text/html;charset=UTF-8");
        @Cleanup PrintWriter objPw = response.getWriter();

        objPw.print(object);
        objPw.flush();
    }

    private String getString(String... strs) {
        StringBuilder buf = new StringBuilder();
        if (null != strs && strs.length > 0) {
            for (String str : strs) { buf.append(str); }
        }
        return buf.toString();
    }

    private Session getShiroSession() {
        return  SecurityUtils.getSubject().getSession();
    }
}
